import { createApp } from 'vue'
import MessageComponent from '@/components/common/Message/index.vue'

class MessageManager {
  constructor() {
    this.instance = null
    this.container = null
    this.init()
  }

  init() {
    // 创建容器
    this.container = document.createElement('div')
    this.container.id = 'message-container'
    document.body.appendChild(this.container)

    // 创建Vue实例
    const app = createApp(MessageComponent)
    this.instance = app.mount(this.container)
  }

  // 成功消息
  success(content, options = {}) {
    return this.show({
      type: 'success',
      content,
      ...options
    })
  }

  // 错误消息
  error(content, options = {}) {
    return this.show({
      type: 'error',
      content,
      duration: 4000, // 错误消息显示时间稍长
      ...options
    })
  }

  // 警告消息
  warning(content, options = {}) {
    return this.show({
      type: 'warning',
      content,
      ...options
    })
  }

  // 信息消息
  info(content, options = {}) {
    return this.show({
      type: 'info',
      content,
      ...options
    })
  }

  // 显示消息
  show(options) {
    if (!this.instance) {
      this.init()
    }
    return this.instance.addMessage(options)
  }

  // 关闭指定消息
  close(id) {
    if (this.instance) {
      this.instance.closeMessage(id)
    }
  }

  // 关闭所有消息
  closeAll() {
    if (this.instance) {
      this.instance.closeAll()
    }
  }

  // 销毁实例
  destroy() {
    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container)
    }
    this.instance = null
    this.container = null
  }
}

// 创建全局实例
const messageManager = new MessageManager()

// 导出便捷方法
export const $message = {
  success: (content, options) => messageManager.success(content, options),
  error: (content, options) => messageManager.error(content, options),
  warning: (content, options) => messageManager.warning(content, options),
  info: (content, options) => messageManager.info(content, options),
  close: (id) => messageManager.close(id),
  closeAll: () => messageManager.closeAll()
}

export default messageManager
